package com.whfc.iot.fse.crane.server;

import com.whfc.common.enums.DeviceType;
import com.whfc.common.util.JSONUtil;
import com.whfc.iot.fse.crane.entity.TwMsg;
import com.whfc.iot.fse.crane.processor.TwUpMsgProcessor;
import com.whfc.iot.fse.crane.processor.TwUpMsgProcessorFactory;
import com.whfc.iot.handler.DefaultServerHandler;
import com.whfc.iot.session.Session;
import com.whfc.iot.session.SessionManager;
import com.whfc.iot.util.LoggingUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2018/11/29 10:41
 */
@ChannelHandler.Sharable
@Component
public class TwServerHandler extends DefaultServerHandler {

    private Logger logger = LoggerFactory.getLogger(TwServerHandler.class);

    @Autowired
    private SessionManager sessionManager;

    @Autowired
    private TwUpMsgProcessorFactory processorFactory;

    public TwServerHandler() {
        super();
    }

    @Override
    public SessionManager getSessionManager() {
        return sessionManager;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("{}", LoggingUtil.format(ctx, "CHANNEL_READ", JSONUtil.toString(msg)));
        try {
            TwMsg reqMsg = (TwMsg) msg;
            String deviceCode = reqMsg.getDeviceSn()+"";
            Integer deviceType = DeviceType.crane.getValue();

            //构建session
            Session session = sessionManager.getSessionByDeviceSn(deviceCode);
            if (session == null) {
                session = sessionManager.createSession(deviceType, deviceCode, ctx.channel());
            }
            //当前channel与session中的channel不一致
            else if (!session.getChannel().equals(ctx.channel())) {
                session.getChannel().close().addListener(future -> {
                    logger.info("旧连接关闭,deviceId={},isDone={},isSuccess={}", deviceCode, future.isDone(), future.isSuccess());
                });
                session = sessionManager.createSession(deviceType, deviceCode, ctx.channel());
            }

            //处理消息
            TwUpMsgProcessor processor = processorFactory.getMsgProcessor(reqMsg.getDataType());
            if (processor != null) {
                processor.processMsg(reqMsg);
            }
        } catch (Throwable ex) {
            logger.error("处理消息失败", ex);
        }
    }
}
